package cn.cvs.controller;

import cn.cvs.pojo.SysUser;
import cn.cvs.service.SysUserService;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class LoginController {
    private Logger logger = Logger.getLogger(LoginController.class);
    @Resource
    private SysUserService sysUserService;

    public LoginController() {
    }

    @RequestMapping({"/toLogin"})
    public String login() {
        return "login";
    }

    @PostMapping({"/login"})
    public String doLogin(@RequestParam String account, @RequestParam String password, HttpServletRequest request, HttpSession session) throws Exception {
        SysUser sysUser = this.sysUserService.login(account, password);
        if (null != sysUser) {
            session.setAttribute("userSession", sysUser);
            return "redirect:/sys/toMain";
        } else {
            request.setAttribute("error", "用户名或密码不正确");
            return "login";
        }
    }

    @RequestMapping({"/logout"})
    public String logout(HttpSession session) {
        session.removeAttribute("userSession");
        return "login";
    }

    @RequestMapping({"/sys/toMain"})
    public String toMain() {
        return "frame";
    }

    @RequestMapping({"/toSysError"})
    public String sysError() {
        return "sysError";
    }
}
